package com.pengpai.pangucms.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pengpai.pangucms.entity.SysFileinfo;
import com.pengpai.pangucms.entity.WebArticle;
import com.pengpai.pangucms.entity.WebCategory;
import com.pengpai.pangucms.service.ISysFileinfoService;
import com.pengpai.pangucms.service.IWebCategoryService;
import com.pengpai.pangucms.utils.R;
import com.pengpai.pangucms.utils.ResultTree;
import com.pengpai.pangucms.utils.UserUtils;
import jakarta.annotation.Resource;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wushuai
 * @since 2023-08-28
 */
@Controller
@RequestMapping("/webCategory")
public class WebCategoryController {

    @Resource
    private IWebCategoryService webCategoryService;
    @Resource
    private ISysFileinfoService sysFileinfoService;

    @GetMapping("/index")
    @PreAuthorize("hasAuthority('web:category:read')")
    public String index(){
        return "admin/web_category/web_category_index";
    }


    @GetMapping("list")
    @ResponseBody
    @PreAuthorize("hasAuthority('web:category:read')")
    public Map<String,Object> list(){
        List<WebCategory> webCategoryList = webCategoryService.list();
        Collections.sort(webCategoryList, new Comparator<WebCategory>() {
            @Override
            public int compare(WebCategory o1, WebCategory o2) {
                if(o1.getSort() == null || "".equals(o1.getSort())) return -1;
                if(o2.getSort() == null || "".equals(o2.getSort())) return -1;
                return o1.getSort() - o2.getSort();
            }
        });
        Map<String, Object> map = new HashMap<>();
        map.put("code",200);
        map.put("msg","");
        map.put("count", webCategoryList.size());
        map.put("data",webCategoryList);

        return map;
    }

    @PostMapping("/del")
    @ResponseBody
    @PreAuthorize("hasAuthority('web:category:delete')")
    public R del(String ids){
        List<Long> list = null;
        if(StrUtil.isNotBlank(ids)){
            list = Stream.of(ids.split(",")).map(Long::parseLong).collect(Collectors.toList());
        }
        webCategoryService.removeByIds(list);
        return R.success();
    }

    @PostMapping("create")
    @ResponseBody
    @PreAuthorize("hasAuthority('sys:permission:create')")
    public R create(WebCategory webCategory){
        webCategory.setCreateUser(UserUtils.CurrentUserName());
        webCategory.setCreateTime(LocalDateTime.now());
        webCategory.setUpdateUser(UserUtils.CurrentUserName());
        webCategory.setUpdateTime(LocalDateTime.now());

        webCategoryService.save(webCategory);
        return R.success();
    }

    @GetMapping("add")
    @PreAuthorize("hasAuthority('web:category:create')")
    public String add(String pid, Model model){
        model.addAttribute("pid", pid);
        return "admin/web_category/web_category_add";
    }

    @GetMapping("selectParent")
    @ResponseBody
    public ResultTree selectParent(WebCategory webCategory) {
        List<WebCategory> list = webCategoryService.list();
        WebCategory baseCategory = new WebCategory();
        baseCategory.setCategoryName("顶级栏目");
        baseCategory.setCategoryId(0);
        baseCategory.setParentId(-1);
        list.add(baseCategory);
        ResultTree tree = new ResultTree();
        tree.setData(list);
        return tree;
    }

    @GetMapping("/edit")
    @PreAuthorize("hasAuthority('web:category:update')")
    public String edit(String id, Model model){
        WebCategory webCategory = webCategoryService.getById(id);
        // 根据fileCode解析图片相对路径
        String uuidName = webCategory.getFileCode();
        QueryWrapper<SysFileinfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("file_code", uuidName);
        SysFileinfo fileinfo = sysFileinfoService.getOne(queryWrapper);
        if(uuidName != null && fileinfo != null){
            String filePath = "/files/" + uuidName + fileinfo.getFileSuff();
            webCategory.setFileCode(filePath);
        }
        if(webCategory.getParentId() == 0){
            webCategory.setRemark("顶级权限");
        }else{
            WebCategory parent = webCategoryService.getById(webCategory.getParentId());
            webCategory.setRemark(parent.getCategoryName());
        }
        model.addAttribute("wc", webCategory);
        return "admin/web_category/web_category_edit";
    }

    @PostMapping("update")
    @ResponseBody
    @PreAuthorize("hasAuthority('web:category:update')")
    public R update(WebCategory webCategory){
        webCategory.setUpdateUser(UserUtils.CurrentUserName());
        webCategory.setUpdateTime(LocalDateTime.now());
        webCategoryService.updateById(webCategory);
        return R.success("栏目信息更新成功！");
    }
}
